<template>
  <chatroom-modal :is-open="isOpen">
    <div class="modify-user-info" @click.stop>
      <chatroom-avatar :info="{ name: name, avatar: avatar }" size="70px" />
      <div class="avatar-actions">
        <input
          type="file"
          accept="image/*"
          @change="onAvatarChange"
          ref="avatarInput"
          class="hidden-input"
        />
        <button class="custom-file-button">选择头像</button>
      </div>
<!--      &lt;!&ndash; 头像 URL 输入 &ndash;&gt;-->
<!--      <chatroom-input-->
<!--        v-model:value="avatar"-->
<!--        label="头像URL"-->
<!--        placeholder="请输入头像URL"-->
<!--        height="40px"-->
<!--        font-size="14px"-->
<!--      />-->
      <chatroom-input
        v-model:value="name"
        label="用户名"
        placeholder="请输入用户名"
        height="40px"
        font-size="14px"
        :readonly="true"
      />
      <chatroom-input
        v-model:value="email"
        label="邮箱"
        placeholder="请输入邮箱"
        height="40px"
        font-size="14px"
        :readonly="true"
      />
      <chatroom-input
        v-model:value="passwordForm.oldPassword"
        type="password"
        label="旧密码"
        placeholder="请输入旧密码,不修改则不填"
        height="40px"
        font-size="14px"
      />
      <chatroom-input
        v-model:value="passwordForm.newPassword"
        type="password"
        label="新密码"
        placeholder="请输入新密码,不修改则不填"
        height="40px"
        font-size="14px"
      />
      <chatroom-input
        v-model:value="passwordForm.confirmPassword"
        type="password"
        label="确认新密码"
        placeholder="请再次输入新密码,不修改则不填"
        height="40px"
        font-size="14px"
      />
      <div class="flex gap-[15px] w-full justify-between mt-[20px]">
        <chatroom-button type="danger" @click="onDeleteAccount" style="background-color: #ff4d4f;">注销账户</chatroom-button>
        <div class="flex gap-[15px]">
          <chatroom-button type="minor" @click="isOpen = false">取消</chatroom-button>
          <chatroom-button @click="onUpdateUser">确定</chatroom-button>
        </div>
      </div>
    </div>
  </chatroom-modal>
</template>
<script setup>
import ChatroomModal from '@/components/ChatroomModal.vue'
import ChatroomAvatar from '@/components/ChatroomAvatar.vue'
import ChatroomInput from '@/components/ChatroomInput.vue'
import ChatroomButton from '@/components/ChatroomButton.vue'
import { reactive, ref, watch } from 'vue'
import { useUserInfoStore } from '@/stores/useUserInfoStore.js'
import UserApi from '@/api/user.js'
import { useToast } from '@/components/ToastProvider.vue'
import router from '@/router/index.js'
import ws from '@/utils/ws.js'

const showToast = useToast()
const isOpen = defineModel('isOpen')

const userInfoStore = useUserInfoStore()
const name = ref(userInfoStore.userName)
const email = ref(userInfoStore.email)
const avatar = ref(userInfoStore.avatar)
const password = ref(userInfoStore.password)

const avatarInput = ref(null)
const avatarPreview = ref('')

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const onAvatarChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  try {
    // Step 1: 使用 FileReader 读取图片
    const reader = new FileReader();
    reader.onload = function (e) {
      const img = new Image();
      img.onload = function () {
        // Step 2: 创建 canvas 并绘制圆形头像
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const size = Math.min(img.width, img.height); // 取最小边作为直径
        canvas.width = size;
        canvas.height = size;

        // 裁剪圆形区域
        ctx.beginPath();
        ctx.arc(size / 2, size / 2, size / 2, 0, Math.PI * 2);
        ctx.closePath();
        ctx.clip();

        // 绘制图片（居中裁剪）
        const dx = (img.width - size) / 2;
        const dy = (img.height - size) / 2;
        ctx.drawImage(img, dx, dy, size, size, 0, 0, size, size);

        // Step 3: 将裁剪后的图片转为 Blob 并上传
        canvas.toBlob((blob) => {
          const formData = new FormData();
          formData.append('file', blob, 'avatar.png'); // 用固定名称上传

          // Step 4: 上传裁剪后的图片
          UserApi.upload(formData).then((res) => {
            if (res.code === 0) {
              avatar.value = res.data
            } else {
              showToast('头像上传失败');
            }
          });
        }, 'image/png');
      };
      img.src = e.target.result;
    };
    reader.readAsDataURL(file);
  } catch (err) {
    showToast('网络错误，请重试！', true);
  }

  event.target.value = '';
};


watch(isOpen, (newVal) => {
  if (newVal) {
    name.value = userInfoStore.userName
    email.value = userInfoStore.email
    avatar.value = userInfoStore.avatar
    password.value = userInfoStore.password
    // 重置密码字段
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  }
})

const onUpdateUser = () => {
  if (!passwordForm.newPassword && !passwordForm.confirmPassword && passwordForm.newPassword !== passwordForm.confirmPassword) {
    showToast('两次输入的新密码不一致！', true)
    return
  }

  if (!passwordForm.oldPassword) {
    passwordForm.newPassword = password.value
  }

  if (passwordForm.oldPassword && passwordForm.oldPassword !== password.value){
    showToast('输入的旧密码错误！', true)
    return
  }

  UserApi.update({ name: name.value, avatar: avatar.value, password: passwordForm.newPassword}).then((res) => {
    if (res.code === 0) {
      userInfoStore.setUserAvatar(avatar.value)
      showToast('修改成功~')
      isOpen.value = false
    }
  })
}

// 新增：注销账号逻辑
const onDeleteAccount = () => {
  if (!confirm('确定要注销账号吗？此操作不可恢复！')) return

  UserApi.deleteAccount(userInfoStore.userId).then(res => {
    if (res.code === 0) {
      showToast('账号已注销~')
      localStorage.removeItem('x-token')
      userInfoStore.clearUserInfo()
      ws.disConnect()
      router.push('/login') // 或 router.push('/login')
    } else {
      showToast(res.message || '注销失败，请重试！', true)
    }
  }).catch(() => {
    showToast('网络错误，请稍后再试！', true)
  })
}
</script>
<style lang="less" scoped>
.modify-user-info {
  width: 600px;
  height: 520px;
  background-image: linear-gradient(
    130deg,
    rgba(var(--background-color), 0.7),
    rgba(var(--background-color), 0.9)
  );
  backdrop-filter: blur(10px);
  border: rgba(var(--background-color), 0.5) 3px solid;
  max-width: 90%;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px;
  gap: 20px;
}
.avatar-actions {
  position: relative;
  display: inline-block;
}

.hidden-input {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
  z-index: 2;
}

.custom-file-button {
  padding: 4px 10px;   // 缩小内边距
  font-size: 12px;     // 字体变小
  border-radius: 3px;  // 边角更圆润或更方正
  background-color: rgb(var(--primary-color));
  color: white;
  border: none;
  cursor: pointer;
  z-index: 1;
}

</style>
